/**
 
 @Name : layui.spinner 时间spinner组件，根据需要再扩展数值的增加减小功能
 @Author：zxh
 @License：MIT
 
 */

layui.define(['jquery', 'util'], function(exports) {
	"use strict";

	var doc = document,
		$ = layui.$,
		util = layui.util
		//字符常量
		,
		MOD_NAME = 'spinner',
		DISABLED = 'layui-disabled',
		ELEM = '.layui-form'

		//构造器
		,
		Class = function(options) {
			this.vision = '1.0.0';
		};
	//渲染
	Class.prototype.render = function(filter) {
		var that = this,
			elemForm = $(ELEM + function() {
				return filter ? ('[lay-filter="' + filter + '"]') : '';
			}()),
			items = {
				spinner: function() {
					var CLASS = 'layui-form-select',
						TITLE = 'layui-select-title',
						spinners = elemForm.find('input[spinner]'),
						events = function(reElem, disabled) {
							var spinner = $(this),
								title = reElem.find('.' + TITLE),
								input = title.find('input'),
								value = input.val()
							if(disabled) return;
							input.focus(function(e) {
								//console.log('获取焦点');
							});
							input.blur(function(e) {
								//console.log('失去焦点');
								//计算时间
								//console.log('失去焦点');
							});
							input.on('click', function(e) {
								var input = $(e.currentTarget)[0];
								getSelectedText(input);
								//$(e.currentTarget).select();
							});
							//事件绑定
							title.on('click', '.layui-spinner-up', function(e) {
								//selectText = input[0].value.substring(selectStart,selectEnd);
								setSelectedText(input[0], 'layui-spinner-up');
								console.log('.up' + input[0].selectionEnd);
							});
							title.on('click', '.layui-spinner-down', function() {
								setSelectedText(input[0], 'layui-spinner-down');
								console.log('.down' + input[0].selectionEnd);
							});
						};
					spinners.each(function(index, spinner) {
						var spinnerDate = new Date();
						spinnerDate.setHours(0, 0, 0);
						var othis = $(this),
							disabled = this.disabled,
							hasRender = othis.next('.' + CLASS);
						if(typeof othis.attr('lay-ignore') === 'string') return othis.show();
						othis.spinnerformat = othis.attr('lay-spinnerformat') || "HH:mm:ss";
						//替代元素
						var reElem = $(['<div spinner class="' + CLASS + (disabled ? ' layui-select-disabled' : '') + '">', '<div class="' + TITLE + '"><input type="text" lay-spinnerformat="' + othis.spinnerformat + '"  value="' + util.toDateString(spinnerDate, othis.spinnerformat) + '" class="layui-input' + (disabled ? (' ' + DISABLED) : '') + '">'
						, '<i class="layui-icon layui-spinner-up">&#xe619;</i><i class="layui-icon layui-spinner-down">&#xe61a;</i></div>', '</div>'].join(''));

						hasRender[0] && hasRender.remove(); //如果已经渲染，则Rerender
						othis.hide();
						othis.after(reElem);
						events.call(this, reElem, disabled);
					});

					function getSelectedText(input, selectionEnd) {
						var value = input.value;
						var result = {};
						var spinnerarray = $(input).attr('lay-spinnerformat').split(':');
						result.selectText = ""; //选中文本
						result.selectIndexed = input.selectionEnd; //没变更之前的光标位置
						result.startIndex = 0; //选中的开始位置
						result.endIndex = 0; //选中的结束位置
						result.arrayIndex = 0; //分隔符所在索引  判断是第几个分隔符需要根据实际format判定
						input.selectionEnd = selectionEnd || input.selectionEnd;
						var selectIndex = 0;
						var selectIndexed = input.selectionEnd;
						if(input.setSelectionRange) {
							input.focus();
							console.log('光标位置' + (input.selectionEnd || 0));
							layui.each(spinnerarray, function(index, item) {
								result.startIndex = selectIndex;
								result.endIndex = selectIndex + item.length;
								result.arrayIndex = index;
								var isbreak = false;
								layui.each(item, function(indexj, itemj) {
									if(result.startIndex <= selectIndexed && result.endIndex >= selectIndexed) {
										console.log(selectIndex);
										isbreak = true;
										return true;
									}
									selectIndex++;
								});

								if(isbreak) {
									return true
								} else {
									selectIndex++;
								}; //索引累加;
							});
							input.setSelectionRange(result.startIndex, result.endIndex);
							result.selectText = input.value.substring(result.startIndex, result.endIndex);

						} else if(input.createTextRange) {
							console.log('test2');
							var range = input.createTextRange();
							range.collapse(true);
							range.moveEnd('character', 0);
							range.moveStart('character', 2);
							range.select();
						}						
						result.selectIndex = input.selectionEnd;
						return result;
					};

					function setSelectedText(input, type) {
						//设置完选中文本需要重新设置选中值
						var result = getSelectedText(input);
						//var selectText =result.selectText;
						var selecindex = input.selectionEnd;
						var setvalue = '';
						var timearray = input.value.split(':');
						var format = $(input).attr('lay-spinnerformat');
						var spinnerDate = new Date(1970, 1, 1, timearray[0], timearray.length > 1 ? timearray[1] : 0, timearray.length > 2 ? timearray[2] : 0);
						if(type == 'layui-spinner-up') {
							spinnerDate.setTime(spinnerDate.getTime() + 1000 * (Math.pow(60, 2 - result.arrayIndex)));
						}
						if(type == 'layui-spinner-down') {
							spinnerDate.setTime(spinnerDate.getTime() - 1000 * (Math.pow(60, 2 - result.arrayIndex)));
						}
						input.value = util.toDateString(spinnerDate, format || 'HH:mm:ss');
						getSelectedText(input, selecindex);
					}
				}
			};
		layui.each(items, function(index, item) {
			item();
		});
		return that;
	};

	//外部接口
	//	var spinner = {
	//		//分页渲染
	//		render: function(options) {
	//			var o = new Class(options);
	//			return o.render();
	//		},
	//		on: function(elem, even, fn) {
	//			elem.attachEvent ? elem.attachEvent('on' + even, function(e) { //for ie
	//				e.target = e.srcElement;
	//				fn.call(elem, e);
	//			}) : elem.addEventListener(even, fn, false);
	//			return this;
	//		}
	//	}
	var spinner = new Class();
	spinner.render();
	exports(MOD_NAME, spinner);
});